<template>
  <div class="points-record-page">
    <!-- 积分总览 -->
    <div class="points-overview">
      <div class="overview-header">
        <h3 class="overview-title">积分总览</h3>
        <van-button 
          size="small" 
          type="default" 
          class="rules-btn"
          @click="goToRules"
        >
          查看规则
        </van-button>
      </div>
      <div class="overview-content">
        <div class="overview-item">
          <div class="item-label">当前积分</div>
          <div class="item-value current-points">{{ currentPoints }}</div>
        </div>
        <div class="overview-item">
          <div class="item-label">累计获得</div>
          <div class="item-value earned-points">+{{ totalEarned }}</div>
        </div>
        <div class="overview-item">
          <div class="item-label">累计使用</div>
          <div class="item-value used-points">-{{ totalUsed }}</div>
        </div>
      </div>
    </div>

    <!-- 筛选标签 -->
    <div class="filter-tabs">
      <div class="tab-list">
        <div 
          v-for="tab in tabs" 
          :key="tab.key"
          class="tab-item"
          :class="{ active: currentTab === tab.key }"
          @click="onTabChange(tab.key)"
        >
          <span class="tab-text">{{ tab.label }}</span>
        </div>
      </div>
    </div>

    <!-- 积分记录列表 -->
    <div class="record-list">
      <div class="list-header">
        <h4 class="list-title">积分记录</h4>
      </div>
      
      <div v-if="filteredRecords.length > 0" class="record-items">
        <div 
          v-for="record in filteredRecords" 
          :key="record.id"
          class="record-item"
          @click="goToDetail(record.id)"
        >
          <div class="record-main">
            <div class="record-info">
              <div class="record-title">{{ record.title }}</div>
              <div class="record-desc">{{ record.description }}</div>
              <div class="record-time">{{ formatTime(record.createTime) }}</div>
            </div>
            <div class="record-points" :class="record.type">
              <span class="points-sign">{{ record.type === 'earned' ? '+' : '-' }}</span>
              <span class="points-value">{{ record.points }}</span>
            </div>
          </div>
          <div v-if="record.status" class="record-status">
            <span class="status-text" :class="record.status">{{ getStatusText(record.status) }}</span>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <van-empty 
          image="search" 
          description="暂无积分记录"
        />
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore && filteredRecords.length > 0" class="load-more">
      <van-button 
        :loading="loading"
        :disabled="loading"
        size="small"
        @click="onLoadMore"
      >
        {{ loading ? '加载中...' : '加载更多' }}
      </van-button>
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="initialLoading" class="page-loading" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getPointsStats, getPointsRecords } from '@/api/points'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const currentPoints = ref(0)
const totalEarned = ref(0)
const totalUsed = ref(0)
const currentTab = ref('all')
const allRecords = ref([])
const filteredRecords = ref([])
const page = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)
const loading = ref(false)
const initialLoading = ref(true)

// 标签配置
const tabs = [
  { key: 'all', label: '全部' },
  { key: 'earned', label: '获得' },
  { key: 'used', label: '使用' },
  { key: 'expired', label: '过期' }
]

// 计算属性
const isLoggedIn = computed(() => userStore.isLogin)

// 生命周期
onMounted(() => {
  if (isLoggedIn.value) {
    loadPointsOverview()
    loadRecords()
  } else {
    initialLoading.value = false
  }
})

onUnmounted(() => {
  // 清理工作
})

// 方法
const loadPointsOverview = async () => {
  try {
    const stats = await getPointsStats()
    
    // 后端返回的是下划线格式的字段名
    currentPoints.value = stats.current_points || 0
    totalEarned.value = stats.total_earned || 0
    totalUsed.value = stats.total_used || 0
  } catch (error) {
    console.error('加载积分统计失败:', error)
    showToast('加载积分信息失败')
  }
}

const loadRecords = async (refresh = false) => {
  if (loading.value) return

  try {
    loading.value = true

    const currentPage = refresh ? 1 : page.value
    const params = {
      start: (currentPage - 1) * pageSize.value,
      count: pageSize.value
    }

    // 如果不是全部标签，添加类型筛选
    if (currentTab.value !== 'all') {
      params.type = currentTab.value
    }

    const response = await getPointsRecords(params)
    const records = response.items || []

    if (refresh) {
      allRecords.value = records
      page.value = 1
      hasMore.value = (response.page || 0) < (response.total_page || 1) - 1
    } else {
      allRecords.value = [...allRecords.value, ...records]
      page.value = currentPage + 1
      hasMore.value = (response.page || 0) < (response.total_page || 1) - 1
    }

    filterRecords()
  } catch (error) {
    console.error('加载积分记录失败:', error)
    showToast('加载记录失败')
  } finally {
    loading.value = false
    initialLoading.value = false
  }
}

const filterRecords = () => {
  let filtered = []

  switch (currentTab.value) {
    case 'all':
      filtered = allRecords.value
      break
    case 'earned':
      filtered = allRecords.value.filter(record => record.type === 'earned')
      break
    case 'used':
      filtered = allRecords.value.filter(record => record.type === 'used')
      break
    case 'expired':
      filtered = allRecords.value.filter(record => record.status === 'expired')
      break
  }

  filteredRecords.value = filtered
}

const onTabChange = (tab) => {
  currentTab.value = tab
  loadRecords(true)
}

const onLoadMore = () => {
  if (!hasMore.value || loading.value) return
  loadRecords()
}

const goToDetail = (id) => {
  router.push({ name: 'PointsRecordDetail', params: { id } })
}

const goToRules = () => {
  router.push({ name: 'PointsRules' })
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  try {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 如果是今天
    if (diff < 24 * 60 * 60 * 1000) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 如果是昨天
    if (diff < 48 * 60 * 60 * 1000) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 其他日期
    return date.toLocaleDateString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit' 
    })
  } catch (error) {
    return timeStr
  }
}

const getStatusText = (status) => {
  const statusMap = {
    'success': '成功',
    'pending': '处理中',
    'failed': '失败',
    'expired': '已过期'
  }
  return statusMap[status] || status
}
</script>

<style lang="scss" scoped>
.points-record-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
}

.points-overview {
  background: linear-gradient(135deg, #157658 0%, #2d8f7a 100%);
  margin: 10px;
  border-radius: 12px;
  padding: 20px;
  color: #fff;
  
  .overview-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .overview-title {
      font-size: 18px;
      font-weight: bold;
      margin: 0;
      color: #fff;
    }
    
    .rules-btn {
      background-color: rgba(255, 255, 255, 0.2);
      border-color: rgba(255, 255, 255, 0.3);
      color: #fff;
      
      &:hover {
        background-color: rgba(255, 255, 255, 0.3);
        border-color: rgba(255, 255, 255, 0.4);
      }
    }
  }
  
  .overview-content {
    display: flex;
    justify-content: space-between;
    
    .overview-item {
      text-align: center;
      flex: 1;
      
      .item-label {
        font-size: 14px;
        opacity: 0.8;
        margin-bottom: 8px;
        display: block;
      }
      
      .item-value {
        font-size: 20px;
        font-weight: bold;
        
        &.current-points {
          color: #fff;
        }
        
        &.earned-points {
          color: #4caf50;
        }
        
        &.used-points {
          color: #ff9800;
        }
      }
    }
  }
}

.filter-tabs {
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px 0;
  
  .tab-list {
    display: flex;
    justify-content: space-around;
    
    .tab-item {
      padding: 8px 16px;
      border-radius: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      .tab-text {
        font-size: 14px;
        color: #666;
      }
      
      &.active {
        background-color: #157658;
        
        .tab-text {
          color: #fff;
        }
      }
      
      &:hover:not(.active) {
        background-color: #f0f0f0;
      }
    }
  }
}

.record-list {
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
  
  .list-header {
    margin-bottom: 15px;
    
    .list-title {
      font-size: 16px;
      font-weight: bold;
      margin: 0;
      color: #333;
    }
  }
  
  .record-items {
    .record-item {
      padding: 15px 0;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover {
        background-color: #f8f8f8;
        padding-left: 10px;
        padding-right: 10px;
        margin-left: -10px;
        margin-right: -10px;
        border-radius: 8px;
      }
      
      &:active {
        background-color: #f0f0f0;
      }
      
      .record-main {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 8px;
        
        .record-info {
          flex: 1;
          
          .record-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 4px;
            display: block;
          }
          
          .record-desc {
            font-size: 14px;
            color: #666;
            margin-bottom: 4px;
            display: block;
          }
          
          .record-time {
            font-size: 12px;
            color: #999;
            display: block;
          }
        }
        
        .record-points {
          font-size: 18px;
          font-weight: bold;
          
          &.earned {
            color: #4caf50;
          }
          
          &.used {
            color: #ff9800;
          }
          
          .points-sign {
            margin-right: 2px;
          }
        }
      }
      
      .record-status {
        .status-text {
          font-size: 12px;
          padding: 2px 8px;
          border-radius: 10px;
          
          &.success {
            background-color: #e8f5e8;
            color: #4caf50;
          }
          
          &.pending {
            background-color: #fff3e0;
            color: #ff9800;
          }
          
          &.failed {
            background-color: #ffebee;
            color: #f44336;
          }
          
          &.expired {
            background-color: #f5f5f5;
            color: #999;
          }
        }
      }
    }
  }
  
  .empty-state {
    padding: 40px 0;
    text-align: center;
  }
}

.load-more {
  text-align: center;
  margin: 20px 0;
  
  .van-button {
    background-color: #157658;
    border-color: #157658;
    color: #fff;
    
    &:hover {
      background-color: #2d8f7a;
      border-color: #2d8f7a;
    }
  }
}

.page-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style> 